import 'dart:math';

import 'package:flutter/material.dart';

/// 还有SliverAnimatedList
class AnimatedListTest extends StatefulWidget {
  @override
  _AnimatedListTestState createState() => _AnimatedListTestState();
}

class _AnimatedListTestState extends State<AnimatedListTest> {
  final _listKey = GlobalKey<AnimatedListState>();
  List<int> _data;
  Tween<Offset> _tween = Tween<Offset>(begin: Offset(1, 0), end: Offset(0, 0));

  @override
  void initState() {
    super.initState();
    _data = [12, 34, 43, 12, 54];
  }

  Widget _myListItem(String text, Animation animation) {
    return SlideTransition(
        position: animation.drive(CurveTween(curve: Curves.bounceOut)).drive(_tween),
        child: Container(
          margin: EdgeInsets.symmetric(vertical: 10.0),
          constraints: BoxConstraints.tight(Size(double.infinity, 70)),
          alignment: Alignment.center,
          child: Text(
            '$text',
            style: TextStyle(color: Colors.white),
          ),
          color: Colors.primaries[int.parse(text) % Colors.primaries.length],
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('AnimatedListState'),
        ),
        body: Stack(
          children: <Widget>[
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 20.0),
              child: AnimatedList(
                key: _listKey,
                itemBuilder: (context, index, animation) => _myListItem(_data[index].toString(), animation),
                initialItemCount: _data.length,
              ),
            ),
            Positioned(
              bottom: 30,
              right: 10,
              child: FloatingActionButton(
                heroTag: 'remove',
                onPressed: _remove,
                child: Icon(Icons.remove),
              ),
            ),
            Positioned(
              bottom: 30,
              right: 70,
              child: FloatingActionButton(
                heroTag: 'add',
                onPressed: _add,
                child: Icon(Icons.add),
              ),
            )
          ],
        ));
  }

  void _remove() {
    int data = _data.last;
    int index = _data.length - 1;
    _data.remove(data);
    _listKey.currentState.removeItem(index, (context, animation) => _myListItem(data.toString(), animation),
        duration: Duration(seconds: 1));
  }

  void _add() {
    int num = Random().nextInt(1000);
    _data.add(num);
    int index = _data.lastIndexOf(num);
    _listKey.currentState.insertItem(index, duration: Duration(seconds: 1));
  }
}
